// pages/map/map.js
var api = require('../../utils/api.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min');
const chooseLocation = requirePlugin('chooseLocation');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModal: false,
    latitude: "",
    longitude: "",
    mapsInfo: "",
    id: "",
    name: "",
    markers: [],
    customCalloutMarkerIds: [],
    times: true,
    community_id: "",
    status: false,
    value: "",
    suggestion: "",
    iconFirst: "/images/icon1.png",
    iconSecond: "/images/icon2.png",
    scale: 14,
    touch: true,
    meter: 2000,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          //未授权
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function(res) {
              if (res.cancel) {
                //取消授权
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function(res) {
                    res.authSetting['scope.userLocation']
                    if (res.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      that.getPositionAlign();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })

              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          that.getPositionAlign();
        } else {
          that.getPositionAlign();
        }
      }
    });

    this.mapCtx = wx.createMapContext("mapId");
    // 聚合
    this.bindEvent();
  },

  // 地址请求
  http: function (latitude, longitude, meter) {
    let that = this;
    api.form_('Scan/map_list', {
        userid_locked: wx.getStorageSync('userid_locked'),
        latitude,
        longitude,
        meter
      },
      null,
      function success(res) {
        console.log(res.data)
        if (res.data.data.list.length != 0) {
          let markArr = []
          let markId = []
          let i = 0
          while (i < res.data.data.list.length) {
            let location = {}
            let newMark = {}
            location.id = i
            newMark.id = i
            newMark.community = res.data.data.list[i].community_name
            location.joinCluster = true // 指定了该参数才会参与聚合
            location.iconPath = "/images/mark.png"
            location.width = "26px"
            location.height = "31px"
            markArr.push(location)
            markId.push(newMark)
            i++
          }
          let newMarks = res.data.data.list.map((item, index) => {
            return {
              ...item,
              ...markArr[index]
            }
          })

          that.setData({
            markers: newMarks,
            tips: res.data.data.tips,
            customCalloutMarkerIds: markId
          })
        }
      }
    )
  },

  getPositionAlign: function () {
    let that = this;

    wx.getLocation({
      type: 'gcj02',
      success(res) {
        wx.setStorageSync('location', {
          latitude: res.latitude,
          longitude: res.longitude
        });

        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });

        that.http(res.latitude, res.longitude, that.data.meter);
      }
    });
  },

  // 地址确认
  certain: function () {
    this.setData({
      markers: []
    })
    this.http(this.data.latitude, this.data.longitude, this.data.meter);
  },

  //监听拖动地图，拖动结束根据中心点更新页面
  mapChange: function (e) {
    let that = this;

    // if (e.type == 'end' && e.causedBy == 'scale') {
    //   that.mapCtx.getScale({
    //     success: function (res) {
    //       console.log(res)
    //     }
    //   })
    // }

    if (e.type == 'end' && e.causedBy == 'drag') {
      that.setData({ markers: [] });
      that.mapCtx.getCenterLocation({
        success: function (res) {
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude
          });
          that.http(res.latitude, res.longitude, that.data.meter);
        }
      });
    }

  },



  // 根据关键词搜索附近位置
  nearby_search: function () {
    var that = this;
    // 调用接口
    qqmapsdk.search({
      keyword: that.data.value, //搜索关键词
      location: that.data.latitude + ',' + that.data.longitude,
      page_size: 20,
      page_index: 1,
      success: function (res) { //搜索成功后的回调
        console.log(res.data)
        var sug = [];
        for (var i = 0; i < res.data.length; i++) {
          sug.push({ // 获取返回结果，放到sug数组中
            title: res.data[i].title,
            id: res.data[i].id,
            addr: res.data[i].address,
            province: res.data[i].ad_info.province,
            city: res.data[i].ad_info.city,
            district: res.data[i].ad_info.district,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng
          });
        }
        that.setData({
          // selectedId: 0,
          // centerData: sug[0],
          // nearList: sug,
          suggestion: sug
        })
        // self.addMarker(sug[0]);
      },
      fail: function (res) {
        //console.log(res);
      },
      complete: function (res) {
        //console.log(res);
      }
    });
  },

  // 输入框
  onChange: function (e) {
    this.setData({
      value: e.detail
    })
  },

  // 搜索框
  onClick: function () {
    qqmapsdk = new QQMapWX({
      key: "5WYBZ-NFMAK-G7OJL-AENBM-RC7XH-GPBGG"
    });

    let that = this
    wx.choosePoi({
      success: function (res) {
        // console.log(res);
        wx.showToast({
          title: '等待中...',
          icon: "loading"
        })
        qqmapsdk.geocoder({
          address: res.address,
          success: function (resdata) {
            const { result } = resdata
            console.log(result);
            wx.hideToast();
            that.setData({
              value: res.name,
              name: res.name,
              latitude: result.location.lat,
              longitude: result.location.lng,
              showModal: false
            });

            that.http(result.location.lat, result.location.lng, that.data.meter);
          }
        })
      }
    })
  },

  // 点击位置
  backfill: function (e) {
    var i = e.currentTarget.dataset.index;
    this.setData({
      i,
      latitude: this.data.suggestion[i].latitude,
      longitude: this.data.suggestion[i].longitude
    });
  },

  // 回到原处
  position: function () {
    let that = this;

    if (that.data.touch) {

      that.setData({
        touch: false,
        showModal: false
      });

      that.mapCtx.moveToLocation({
        success: function (res) {
          let {
            latitude,
            longitude
          } = wx.getStorageSync('location');
  
          that.setData({
            latitude,
            longitude,
            i: null,
            markers: []
          });
  
          that.http(latitude, longitude, that.data.meter);
        },
        fail: function (err) {
          console.log(err);
        }
      });

      setTimeout(() => {
        that.setData({
          touch: true
        });
      }, 3000)
    }
  },

  // 聚合
  bindEvent: function () {
    this.mapCtx.initMarkerCluster({
      enableDefaultStyle: false,
      zoomOnClick: true,
      gridSize: 60
    });

    // enableDefaultStyle 为 true 时不会触发改事件
    this.mapCtx.on('markerClusterCreate', res => {
      console.log('clusterCreate', res)
      const clusters = res.clusters
      const markers = clusters.map(cluster => {

        const {
          center,
          clusterId,
        } = cluster

        return {
          ...center,
          width: 0,
          height: 0,
          clusterId, // 必须
          iconPath: "/images/mark.png",
          width: 39,
          height: 46,
        }
      })

      this.mapCtx.addMarkers({
        markers,
        clear: false,
        complete(res) {
          console.log('clusterCreate addMarkers', res)
        }
      })
    })
  },

  // 缩放
  region: function name() {
    this.mapCtx.getScale({
      success: function (res) {
        console.log(res);
      },
      fail: function (err) {
        console.log(err);
      }
    })
  },

  // 取消
  hideModal: function () {
    this.setData({
      showModal: false
    })
  },

  // 确定
  onConfirm: function () {

    wx.openLocation({
      latitude: this.data.latitude/1, // 纬度，范围为-90~90，负数表示南纬
      longitude: this.data.longitude/1, // 经度，范围为-180~180，负数表示西经
      name: this.data.name
    });
  },

  // 错误上报
  onError: function () {
    let that = this
    if (that.data.times) {
      that.setData({
        times: false,
      })

      api.form_("Scan/correct", {
        "community_id": that.data.community_id,
        "userid_locked": wx.getStorageSync('userid_locked'),
      }, null, function success(res) {
        console.log(res.data);

        wx.showModal({
          showCancel: false,
          content: res.data.msg
        })
      })

      setTimeout(() => {
        that.setData({
          times: true
        })
      }, 3000)
    }
  },

  marked: function (e) {
    let community_id = this.data.markers[e.detail.markerId].community_id;
    let that = this;
     api.form_('scan/map_list_more', {
        userid_locked: wx.getStorageSync('userid_locked'),
        community_id
      },
      null,
      function success(res) {
        console.log(res.data)
        that.setData({
          showModal: true,
          mapsInfo: res.data.data,
          name: res.data.data.community_name,
          status: false,
          community_id,
          latitude: res.data.data.latitude,
          longitude: res.data.data.longitude
        })
      }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // const location = chooseLocation.getLocation(); 
    // console.log(location);
    // if (location) {
    //   this.setData({
    //     latitude: location.latitude,
    //     longitude: location.longitude
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('location');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})